<?php
namespace app\store\controller;

use app\store\model\Region;
use app\common\model\GetTui as GetTuiModel;
/**
 * 4s店面管理
 * Class User
 * @package app\store\controller
 */
class Shop extends Controller
{
    /**
     * 4s店面列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
		$where = [];
		$shop_name = $this->request->param("shop_name/s" , '');
		if( $shop_name ) {
			$where['shop_name'] = ['like' , '%'.$shop_name.'%'];
		}
		$tel = $this->request->param("tel/s" , '');
		if( $tel ) {
			$where['tel'] = $tel;
		}
		$province = $this->request->param("province/d" , 0);
		if( $province ) {
			$where['province'] = $province;
		}
		$city = $this->request->param("city/d" , 0);
		if( $city ) {
			$where['city'] = $city;
		}
		$area = $this->request->param("area/d" , 0);
		if( $area ) {
			$where['area'] = $area;
		}
        $list = db("shop")->where($where)->order(['shop_id' => 'DESC'])->paginate(15, false, ['query' => $this->request->request()])->each(function($item  , $key){
            //获得分配的机油数量
            $item['stock'] = db("engineoil_stock_log")->where(['shop_id' => $item['shop_id'] , 'type' => 3])->sum("stock");
            return $item;
        });
		$area = json_encode(Region::getCacheTree());
		//获得机油列表
		$engineoil_list = db("engineoil")->where('`status` = 1 AND `stock` > 0')->select()->toArray();
        return $this->fetch('index', compact('list','area','engineoil_list'));
    }
    
    /**
     * 新增
     */
    public function add() {
        return $this->post();
    }
    
    /**
     * 修改
     */
    public function edit() {
        $id = $this->request->param('shop_id/d' , 0);
        if( !$data = db("shop")->where(['shop_id' => $id])->find()){
            $this->error("数据不存在");
        }
        $data['transport_license'] = json_decode($data['transport_license'],true);
        $data['shop_image'] = json_decode($data['shop_image'],true);
        $data['workshop_image'] = json_decode($data['workshop_image'],true);
        $data['reception_image'] = json_decode($data['reception_image'],true);
        $data['office_image'] = json_decode($data['office_image'],true);
        if( $data['user_id'] > 0 ) {
            $data['user_info'] = db('user')->where(['user_id' => $data['user_id']])->field("nickname,user_id,avatar")->find();
        } 
        return $this->post( $data );
    }
    
    /*
     * 删除
     */
    public function delete() {
        $id = $this->request->post('shop_id' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
        $res = db('shop')->where(['shop_id' => $id])->delete();
        if( $res ) {
            $this->success('删除成功');
        } else {
            $this->error("操作失败");
        }
    }
    
    private function post($save_data = []) {
        if( $this->request->isAjax() ) {
            $params = $this->postData('shop');
            $params['transport_license'] = isset($params['transport_license']) ? json_encode($params['transport_license']) : '';
            $params['shop_image'] = isset($params['shop_image']) ? json_encode($params['shop_image']) : '';
            $params['workshop_image'] = isset($params['workshop_image']) ? json_encode($params['workshop_image']) : '';
            $params['reception_image'] = isset($params['reception_image']) ? json_encode($params['reception_image']) : '';
            $params['office_image'] = isset($params['office_image']) ? json_encode($params['office_image']) : '';
            $params['province_name'] = db("region")->where(['id' => $params['province']])->value("name");
            $params['city_name'] = db("region")->where(['id' => $params['city']])->value("name");
            $params['area_name'] = db("region")->where(['id' => $params['area']])->value("name");
			$params['type'] = !$params['type'] ? $this->error('请选择类型') : ','.implode("," , $params['type']).',';
            $shop_id = $this->request->post('shop_id/d' , 0);
            if( $shop_id > 0 ) {
                $res = db("shop")->where(['shop_id' => $shop_id])->update($params);
                if( $res ) {
                    $this->success('4s店修改成功');
                } else {
                    $this->error('服务中心修改失败');
                }
            }else {
                $params['create_time'] = time();
                $res = db("shop")->insert($params);
                if( $res ) {
                    $this->success('服务中心添加成功');
                } else {
                    $this->error('服务中心添加失败');
                }
            }
        }
        $area = json_encode(Region::getCacheTree());
        return $this->fetch('' , compact('area' , 'save_data'));
    }
	
	/**
	 * 数据统计
	 */
	public function dataCount() {
		$shop_id = $this->request->param("shop_id/d" , 0);
		if( $shop_id <= 0 ) $this->error("数据错误");
		$data = [
			'sh' => db("shop_yuyue_service")->where(['status' => 0, 'shop_id' => $shop_id])->count(),
			'ok' => db("shop_yuyue_service")->where(['status' => 1, 'shop_id' => $shop_id])->count(),
			'start' => db("shop_yuyue_service")->where(['status' => 2, 'shop_id' => $shop_id])->count(),
			'over' => db("shop_yuyue_service")->where(['status' => 3, 'shop_id' => $shop_id])->count(),
			'hsd' => db("shop_yuyue_service")->where(['is_settlement' => 1, 'settlement_status' => 0, 'shop_id' => $shop_id])->count(),
			'hsy' => db("shop_yuyue_service")->where(['is_settlement' => 1, 'settlement_status' => 1, 'shop_id' => $shop_id])->count(),
			'hsw' => db("shop_yuyue_service")->where(['is_settlement' => 1, 'settlement_status' => 3, 'shop_id' => $shop_id])->count(),
			'hsz' => db("shop_yuyue_service")->where(['is_settlement' => 1, 'shop_id' => $shop_id])->count(),
			'jys' => db("engineoil_replenishment")->where(['status' => 0, 'shop_id' => $shop_id])->sum('stock') . ' 桶',
			'jyb' => db("engineoil_replenishment")->where(['status' => 1, 'shop_id' => $shop_id])->sum('stock') . ' 桶',
			'jyc' => db("engineoil_replenishment")->where(['status' => ['in' , '2,3,4'], 'shop_id' => $shop_id])->sum('stock') . ' 桶',
			'jyz' => db("engineoil_shop")->where(['shop_id' => $shop_id])->sum('total_stock_num'),
			'y_sy' => round( db("engineoil_shop")->where(['shop_id' => $shop_id])->sum('stock_num') , 2 ). ' 升',
			'y_use' => round( db("engineoil_shop_log")->where(['shop_id' => $shop_id , 'type' => 2])->sum('num') , 2 ). ' 升',
			'y_use_h' => round( db("engineoil_shop_log")->where(['shop_id' => $shop_id,'use_type' => 1 , 'type' => 2])->sum('num') , 2 ). ' 升',
			'y_use_b' => round( db("engineoil_shop_log")->where(['shop_id' => $shop_id,'use_type' => 2 , 'type' => 2])->sum('num') , 2 ). ' 升',
		];
		$this->success("success" , '' , $data);
	}
	
	/**
	 * 获得库存机油列表
	 */
	public function getStockList() {
		$shop_id = $this->request->param("shop_id/d" , 0);
		if( $shop_id <= 0 ) $this->error("数据错误");
		$list = db("engineoil")->alias("es")->where(['s.shop_id' => $shop_id])->join("engineoil_shop s",'s.engineoil_id = es.id')->field("s.id as esid,s.shop_id,es.id,s.stock_num,s.total_stock_num,s.last_instock_time,es.thumb,es.title,es.model_number,es.brand")->select()->toArray();
		$this->success("success" , '' , $list);
	}
	
    public function export()
    {
		$where = [];
		$shop_name = $this->request->param("shop_name/s" , '');
		if( $shop_name ) {
			$where['shop_name'] = ['like' , '%'.$shop_name.'%'];
		}
		$tel = $this->request->param("tel/s" , '');
		if( $tel ) {
			$where['tel'] = $tel;
		}
		$province = $this->request->param("province/d" , 0);
		if( $province ) {
			$where['province'] = $province;
		}
		$city = $this->request->param("city/d" , 0);
		if( $city ) {
			$where['city'] = $city;
		}
		$area = $this->request->param("area/d" , 0);
		if( $area ) {
			$where['area'] = $area;
		}
        $list = db("shop")->where($where)->order(['shop_id' => 'DESC'])->select()->each(function($item  , $key){
            //获得分配的机油数量
            $item['stock'] = db("engineoil_stock_log")->where(['shop_id' => $item['shop_id'] , 'type' => 3])->sum("stock");
            return $item;
        })->toArray();
		$new_data = [];
		if( $list ){
			foreach( $list as $k => $v ) {
				$new_data[] = [
					'shop_id' => $v['shop_id'],
					'shop_name' => $v['shop_name'],
					'type' => $v['type'] == 1 ? '机油' : '柴油',
					'province_name' => $v['province_name'],
					'city_name' => $v['city_name'],
					'area_name' => $v['area_name'],
					'address' => $v['address'],
					'contact' => $v['contact'],
					'tel' => $v['tel'],
					'legal_person' => $v['legal_person'],
					'legal_person_mobile' => $v['legal_person_mobile'],
					'saletime' => $v['saletime'],
					'create_time' => date("Y-m-d H:i:s" , $v['create_time'])
				];
			}
		}
		$field = ['ID' , '名称' , '类型' , '省' , '市' , '区' , '详细地址' , '联系人' , '联系电话' , '法人' , '法人电话' , '营业时间' , '创建时间'];
		\app\common\extend\Excel::export($new_data , $field);
	}
	
	//机油分配
	public function fenpei() {
		$id = $this->request->post('id/d' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
		$data = $this->request->post('data/d' , 0);
        if( $data <= 0 ) $this->error('请选择分配的机油');
		$stock = $this->request->post('stock/d' , 0);
        if( $stock <= 0 ) $this->error('请输入分配的机油数量');
        
		$info = db('shop')->where(['shop_id' => $id])->find();
        if( !$info ) $this->success('数据异常');
		
		$jiyou_info = db("engineoil")->where(['id' => $data,'status' => 1])->find();
		if( !$jiyou_info ) $this->error("数据错误");
		if( $jiyou_info['stock'] < $stock ) $this->error("最多只能分配【{$jiyou_info['stock']}】");
		//计算分配容量
		$capacity = $jiyou_info['capacity'] * $stock;
		if( $stock_info = db("engineoil_shop")->where(['engineoil_id' => $data , 'shop_id' => $id])->find() ) {
			db("engineoil_shop")->where(['id' => $stock_info['id']])->update(['last_instock_time' => time(),'stock_num' => $stock_info['stock_num'] + $capacity , 'total_stock_num' => $stock_info['total_stock_num'] + $capacity]);
		} else {
			db("engineoil_shop")->insert([
				'shop_id' => $id,
				'engineoil_id' => $data,
				'stock_num' => $capacity,
				'capacity' => $jiyou_info['capacity'],
				'total_stock_num' => $capacity,
				'last_instock_time' => time(),
				'create_time' => time()
			]);
		}
		db("engineoil_stock_log")->insert([
			'eid' => $data,
			'type' => 3,
			'content' => '平台主动分配【'.$stock.'】桶',
			'stock' => $stock,
			'shop_id' => $id,
			'create_time' => time(),
		]);
		
		db("engineoil_shop_log")->insert([
			'shop_id' => $id,
			'engineoil_id' => $data,
			'type' => 1,
			'num' => $capacity,
			'content' => '平台主动分配产品【'.$jiyou_info['title'].'】机油量【'.$capacity.'】升',
			'create_time' => time()
		]);
		$obj = new GetTuiModel;
		$obj->sendToClient($info['user_id'] , '平台机油分配' , '平台主动分配产品【'.$jiyou_info['title'].'】机油量【'.$capacity.'】升，详情请在商家中心查看');
		db("engineoil")->where(['id' => $data])->update(['stock' => $jiyou_info['stock'] - $stock]);
		
		$this->success("分配成功");
	}
	
	public function stockupdate() {
		$id = $this->request->post('id/d' , 0);
        if( $id <= 0 ) $this->error('参数错误，请核对');
		$stock = $this->request->post('stock/d' , 0);
        if( !$stock ) $this->error('请输入要调整的机油数量');
		$info = db("engineoil_shop")->where(['id' => $id])->find();
		if( !$info ) {
			$this->error('数据不存在');
		}
		$engineoil = db("engineoil")->where(['id' => $info['engineoil_id']])->find();
		if( $stock % $engineoil['capacity'] > 0 ) {
			$this->error('调整次机油库存必须为【'.$engineoil['capacity'].'】的倍数');
		}
		$save_data = ['stock_num' => $info['stock_num'] + $stock];
		if( $stock > 0 ) {
			$save_data['total_stock_num'] = $info['total_stock_num'] + $stock;
		}
		$res = db( "engineoil_shop" )->where( [ 'id' => $id ] )->update( $save_data );
		if( $res ) {
			$type = $stock > 0 ? 1 : 3;
			db("engineoil_shop_log")->insert([
				'shop_id' => $info['shop_id'],
				'engineoil_id' => $info['engineoil_id'],
				'type' => $type,
				'num' => abs( $stock ),
				'content' => '平台库存调整【'.$stock.'】升',
				'create_time' => time()
			]);
			$total_stock = abs( $stock ) / $engineoil['capacity'];
			db("engineoil")->where(['id' => $info['engineoil_id']])->update(['stock' => $engineoil['stock'] + ($type == 1 ? $total_stock : -$total_stock )]);
			$shop_info = db("shop")->where(['shop_id' => $info['shop_id']])->find();
			db("engineoil_stock_log")->insert([
				'eid' => $info['engineoil_id'],
				'type' => $type == 1 ? 3 : 4,
				'content' => $type == 1 ? '库存调整，自动给【'.$shop_info['shop_name'].'】分配库存' : '库存调整，商家【'.$shop_info['shop_name'].'】退回库存',
				'stock' => $total_stock,
				'shop_id' => $info['shop_id'],
				'create_time' => time(),
			]);
			$this->success("库存调整成功");
		} else {
			$this->error("库存调整失败");
		}
	}
}
